import java.io.*;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description: 从文件中获取姓名，统计每个名字的出现次数，并打印名字和次数，并指明第一个只出现了一次的名字
 */
public class FileTest12 {
    public static void main(String[] args) {
        try(Reader reader = new BufferedReader(new FileReader("d:/test.txt"))) {
            HashMap<String, Integer> map = new HashMap<>();
            StringBuilder stringBuilder = new StringBuilder();
            // 标记当前位置，并保证在mark之后最多可以读取参数个字符数据，如果超过，mark失效
            // 此时调用 reset 想要返回到mark标记的位置就会抛出异常
            reader.mark(1000000000);
            while(true) {
                char[] buffer = new char[5];
                int count = reader.read(buffer);
                if(count == -1) {
                    break;
                }
                int index = 0;
                while(index < count) {
                    while(index < count && buffer[index] != ' ') {
                        stringBuilder.append(buffer[index++]);
                    }
                    if(index >= count) {
                        break;
                    }
                    String name = stringBuilder.toString();
                    map.put(name, map.getOrDefault(name, 0) + 1);
                    stringBuilder.delete(0, stringBuilder.length());
                    index++;
                }
            }
            reader.reset();
            while(true) {
                char[] buffer = new char[5];
                int count = reader.read(buffer);
                if(count == -1) {
                    break;
                }
                int index = 0;
                while(index < count) {
                    while(index < count && buffer[index] != ' ') {
                        stringBuilder.append(buffer[index++]);
                    }
                    if(index >= count) {
                        break;
                    }
                    String name = stringBuilder.toString();
                    if(map.getOrDefault(name, 0) == 1) {
                        System.out.println("姓名：" + name + " 次数：" + 1);
                        break;
                    }
                    stringBuilder.delete(0, stringBuilder.length());
                    index++;
                }
                if(index < count) {
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
